package com.sqx.modules.health.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqx.modules.health.common.Constants;
import com.sqx.modules.health.common.Result;
import com.sqx.modules.health.entity.*;
import com.sqx.modules.health.service.*;
import com.sqx.modules.health.utils.HttpUtils;
import com.sqx.modules.health.utils.MyBeanUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author gxy
 * @since 2022-07-28
 */

@Api(value = "", tags = "", description = "")
@RestController
@RequestMapping("/health/surveyrecord")
public class SurveyrecordController {
    @Autowired
    private ISurveyrecordService surveyrecordService;
    @Autowired
    private IRecordService recordService;
    @Autowired
    private IRecordsetService recordsetService;
    @Autowired
    private INcgDeviceWatchService watchService;
    @Autowired
    private IReportService reportService;

    // 新增或更新
    @PostMapping("/save")
    @ApiOperation(value = "新增或更新", notes = "新增或更新")
    public Result save(@RequestBody Surveyrecord surveyrecord){
        return Result.success(surveyrecordService.save(surveyrecord));
    }

    // 根据ID删除
    @DeleteMapping("/del/{id}")
    @ApiOperation(value = "根据ID删除", notes = "根据ID删除")
    public Result delete(@PathVariable Integer id){
        return Result.success(surveyrecordService.removeById(id));
    }

    // 根据IDS删除
    @PostMapping("/del/batch")
    @ApiOperation(value = "根据IDS删除", notes = "根据IDS删除")
    public Result deleteBatch(@RequestBody List<Integer> ids){
        return Result.success(surveyrecordService.removeByIds(ids));
    }

    // 查询全部
    @GetMapping("/findAll")
    @ApiOperation(value = "查询全部", notes = "查询全部")
    public Result findAll(){
        return Result.success(surveyrecordService.list());
    }

    // 根据ID查询一条记录
    @GetMapping("/findOne")
    @ApiOperation(value = "根据ID查询一条记录", notes = "根据ID查询一条记录")
    public Result findOne(@PathVariable Integer id){
        return Result.success(surveyrecordService.getById(id));
    }

    // 分页查询
    @GetMapping("/findPage")
    @ApiOperation(value = "分页查询", notes = "分页查询")
    public Result findPage(@RequestParam Integer pageNum,@RequestParam Integer pageSize,
                           @RequestParam(required = false, defaultValue = "") Long recordId,
                           @RequestParam(required = false,defaultValue = "") String patid){

        if (checkPatid(patid)) {
            synchronous(recordId); // 同步数据
        }
        //把pdf保存到服务器
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("recordid",recordId);
        jsonObject.put("paintid",patid);
        //获取数据
        Boolean re = reportService.fillBloodTemplate(jsonObject); // 生成报告

        QueryWrapper<Surveyrecord> queryWrapper = new QueryWrapper<Surveyrecord>()
                .eq(ObjectUtil.isNotEmpty(patid), "patid", patid)
                .orderByDesc("sampleDate");
        List<Surveyrecord> list = surveyrecordService.list(queryWrapper);
//        surveyrecordService.page(new Page<>(pageNum,pageSize),queryWrapper);
//        List<NcgDeviceWatchVO> ncgDeviceWatchVOS = MyBeanUtil.collectionCopy(page.getRecords(), NcgDeviceWatchVO.class);
        Page<Surveyrecord> result = new Page<>();
        result.setRecords(list);
        result.setTotal(list.size());
//        return Result.success(surveyrecordService.page(new Page<>(pageNum,pageSize),queryWrapper));
        return Result.success(result);
    }

    private Boolean checkPatid(String patid) {
        QueryWrapper<Surveyrecord> queryWrapper = new QueryWrapper<Surveyrecord>().eq(ObjectUtil.isNotEmpty(patid), "patid", patid);
        List<Surveyrecord> list = surveyrecordService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            return true;
        }
        return false;
    }

    public void synchronous(Long recordId) {
        Record record = recordService.getById(recordId);
        List<Surveyrecord> remoteData = getRemoteData(record);
        surveyrecordService.saveBatch(remoteData);
//        LambdaUpdateWrapper<Record> updateWrapper = new LambdaUpdateWrapper<Record>()
//                .set(Record::getFlag, 1).eq(Record::getId, recordId);
//        recordService.update(updateWrapper);
    }

    /**
     * 获取远程数据
     * @param record
     * @return
     */
    private List<Surveyrecord> getRemoteData(Record record) {
        List<Saihong> collect = new ArrayList<>();
        List<Surveyrecord> surveyrecords = new ArrayList<>();
        try {
            String starttime = ObjectUtil.isEmpty(record.getRecordtime()) ? DateUtil.beginOfDay(new Date()).toString() : record.getRecordtime();
            String endtime = DateUtil.date().toString();
            Map<String, Object> params = new HashMap<>();
            params.put("deviceMac", record.getImei());
            params.put("starttime", starttime);
            params.put("endtime", endtime);
            String param = JSON.toJSONString(params);
            System.out.println("----------"+param);
            String result = HttpUtils.sendPost("http://taiyibp.tjtzkt.com/getBpDatas.aspx", param);
            JSONObject jsonObject1 = JSONObject.parseObject(result);
            List<Object> data = (List<Object>) jsonObject1.get("data");
            List<Saihong> saihongs = new ArrayList<>();
            System.out.println("++++++++"+data);
            if (data != null) {
                for (int i = 0; i < data.size(); i++) {
                    Saihong saihong = new Saihong();
                    BeanUtil.copyProperties(data.get(i), saihong);
                    saihongs.add(saihong);
                }
//                collect = saihongs.stream().filter(saihong -> ObjectUtil.equals(saihong.getIsValidName(), "有效数据")).collect(Collectors.toList());
                collect = saihongs.stream().filter(saihong -> saihong.getIsValid() == 1).collect(Collectors.toList());
            }
            surveyrecords = MyBeanUtil.collectionCopy(collect, Surveyrecord.class);
            surveyrecords.forEach(surveyrecord -> {
                surveyrecord.setPatid(record.getPatid());
            });
            return surveyrecords;
        } catch (Exception e) {
            e.printStackTrace();
            return surveyrecords;
        }
    }

    @GetMapping("/deviceBack")
    public Result deviceBack(@RequestParam(required = false, defaultValue = "") String imei,
                             @RequestParam(required = false, defaultValue = "") Long recordId) {

        Recordset recordset = recordsetService.getLast(imei);
        recordset.setStatus(1);
        recordset.setEnddate(LocalDateTime.now());
        boolean saveOrUpdate = recordsetService.saveOrUpdate(recordset);

        LambdaUpdateWrapper<NcgDeviceWatch> wrapper = new LambdaUpdateWrapper<NcgDeviceWatch>()
                .set(NcgDeviceWatch::getDoctorid, null)
                .set(NcgDeviceWatch::getUid, null)
                .set(NcgDeviceWatch::getStatus, 3)
                .eq(ObjectUtil.isNotEmpty(imei), NcgDeviceWatch::getImei, imei);
        boolean device = watchService.update(wrapper);

        LambdaUpdateWrapper<Record> updateWrapper = new LambdaUpdateWrapper<Record>()
                .set(Record::getFlag, 1)
                .eq(Record::getId, recordId);
        recordService.update(updateWrapper);

        if (device && saveOrUpdate) {
            return Result.success("设备归还成功");
        } else {
            return Result.error(Constants.CODE_500, "归还失败,请联系管理员");
        }
    }
}

